package class

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"project/pkg/models"
	"project/pkg/validate"
	"strconv"
	"strings"
)

// UpdateClassInfo 更新班级的信息
func (h CHandler) UpdateClassInfo(c *gin.Context) {
	var (
		teacherInfo *models.TeacherInfo
	)
	resp := new(models.RespData)
	req := new(models.UpdateClassInfoReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("Student:SearchClassInfoByTeacherID with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("Student:SearchClassInfoByTeacherID with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	fmt.Println("_----", req.TeacherId)
	//查找教师信息
	texist, teacherInfo, err := h.M.TeacherCheckExistByID(strconv.Itoa(req.TeacherId))
	if err != nil {
		zap.L().Error("Class:SearchClassInfoByTeacherID h.M.TeacherCheckExistByID err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	if texist {
		classList := strings.Split(teacherInfo.ClassList, "|")
		if classList[0] == "" {
			return
		}
		for _, v := range classList {
			if v == "" {
				continue
			}
			//更新对应班级的信息
			//1查班级
			cexisr, classInfo, err := h.M.ClassCheckExistByID(v)
			if err != nil {
				zap.L().Error("Class:SearchClassInfoByTeacherID  h.M.ClassCheckExistByID err", zap.Error(err))
				resp.SendServerBusy(c)
				return
			}
			if cexisr {
				//2.查学生表更新信息
				people, leave, nowPeople, err := h.M.StudentUpdateClassInfo(strconv.Itoa(int(classInfo.ID)))
				if err != nil {
					zap.L().Error("Class:SearchClassInfoByTeacherID  h.M.StudentUpdateClassInfo err", zap.Error(err))
					resp.SendServerBusy(c)
					return
				}
				classInfo.PeopleCount = people
				classInfo.LeaveCount = leave
				classInfo.NowPeopleCount = nowPeople
				//更新班级
				err = h.M.ClassUpdateInfoBuID(classInfo)
				if err != nil {
					zap.L().Error("Class:SearchClassInfoByTeacherID h.M.ClassUpdateInfoBuID err", zap.Error(err))
					resp.SendServerBusy(c)
					return
				}
			}
		}
		resp.SendSuccess(c)
	}
}
